<template>
  <div id="map">
    <Menus :title="mapname" :home="true" />
    <div class="map-wrap">
      <div class="map-area-list">
        <div class="service-content">
          <div class="choose-item">

            <div class="content-block-title">请选择您要查询的地点</div>
            <div class="option-area-select">
              <a class="btn btn-default btn-lg" @click="setArea(codearea)" :class="{'btn-primary': code==codearea}">
                <span>全部</span>
              </a>
              <a class="btn btn-default btn-lg" v-for="(item,key) in residence" :key="'key-'+key" @click="setArea(key)" :class="{'btn-primary': code==key}">
                <span>{{item.alias}}</span>
              </a>

              <a class="btn btn-default btn-lg" @click="show_select_areacode=true">
                <span>其他州市</span>
              </a>
            </div>
            <div v-if="org_type==2">
              <div class="content-block-title">请选择您要查询的类别</div>
              <div class="option-area-select">
                <a class="btn btn-default btn-lg" v-for="(item,key) in dispute_list" :key="'key-'+key" @click="setType(key)" :class="{'btn-primary': dispute==key}">
                  <span>{{item}}</span>
                </a>
              </div>
            </div>
            <div class="content-block-title" v-if="masData.length">输入名称关键字可以快速搜索</div>
            <div class="search-content" v-if="masData.length">
              <input type="text" class="form-control input-lg" placeholder="请输入名称关键字" v-model="searchinfo">
            </div>
            <div v-else class="tips">
              暂时无法获取数据
            </div>
            <div class="list-block">
              <ul v-if="dispute === '0' && !search_flag">
                <li v-for="(item,index) in masData" :key="'key-'+index">
                  <a href="javascript:void(0)" @click="getToPoint(index)" class="item-link item-content" :class="{on:selected==index}">
                    <div class="item-inner">
                      <div class="item-title">
                        <div class="ht">
                          <span>{{index+1}}</span>
                          <strong>{{item.name}}</strong>
                        </div>
                        <p>地址：{{item.address}}
                          <br> 电话：{{item.tell}}
                        </p>
                      </div>
                    </div>
                  </a>
                </li>
              </ul>
              <ul v-else-if="dispute && !search_flag">
                <li v-for="(item,index) in masData_dispute" :key="'key-'+index">
                  <a href="javascript:void(0)" @click="getToPoint(item.index)" class="item-link item-content" :class="{on:selected==index}">
                    <div class="item-inner">
                      <div class="item-title">
                        <div class="ht">
                          <span>{{index+1}}</span>
                          <strong>{{item.name}}</strong>
                        </div>
                        <p>地址：{{item.address}}
                          <br> 电话：{{item.tell}}
                        </p>
                      </div>
                    </div>
                  </a>
                </li>
              </ul>
              <ul v-else-if="search_flag">
                <li v-for="(item,index) in masData_search" :key="'key-'+index">
                  <a href="javascript:void(0)" @click="getToPoint(item.index)" class="item-link item-content" :class="{on:selected==index}">
                    <div class="item-inner">
                      <div class="item-title">
                        <div class="ht">
                          <span>{{index+1}}</span>
                          <strong>{{item.name}}</strong>
                        </div>
                        <p>地址：{{item.address}}
                          <br> 电话：{{item.tell}}
                        </p>
                      </div>
                    </div>
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <div id="map-container"></div>
    </div>
    <div class="select_area" v-if="show_select_area">
      <div class="wrap">
        <div class="ht">请选择您所在区域</div>
        <div class="content">
          <a v-if="key!=='530100'" v-for="(item,key) in residence" :key="'key-'+key" @click="setArea(key)">
            <span>{{item}}</span>
          </a>
        </div>
      </div>
    </div>

    <div class="select_area" v-if="show_select_areacode">
      <div class="wrap">
        <div class="ht">请选择地区</div>
        <div class="content">
          <a v-for="(item,key) in $root.area" :key="'key-'+key" @click="setArea(key, true)">
            <span>{{item.name}}</span>
          </a>
        </div>
      </div>
    </div>

  </div>
</template>
<script>
import { org_type_name, residence, dispute_list } from '@/config.js'
// import { getDistanceSortList } from "../fun"
import Menus from '../components/Menu.vue'
import Dialogs from '../components/Dialog'
import TMap from '../functions/map'
// import api from '../datas/api'

function getDistanceSortList(arr) {
  return arr.sort((a, b) => {
    return a.distance - b.distance
  })
}

export default {
  data() {
    return {
      selected: '',
      residence: '',
      dispute_list,
      searchinfo: '',
      search_flag: false,
      name: '',
      org_type: 1,
      code: '',
      codearea: '',
      dispute: 0,
      show_select_area: false,
      show_select_areacode: false,
      userLocation: '',
      map_id: '',
      qq: '',
      map: '',
      markers_array: [],
      zoom: 16,
      map_center: [25.033481, 102.710082],
      masData: [],
      masData_dispute: [],
      masData_search: [],
      infoWin: '',
      alert: {
        show: false,
        info: ''
      },
      showlist: false
    }
  },
  computed: {
    codename() {
      return residence[this.code]
    },
    mapname() {
      return org_type_name[this.org_type]
    }
  },
  methods: {
    async setArea(key, is_web_code = false) {
      this.code = key
      console.log(key)
      this.show_select_area = false
      this.show_select_areacode = false
      this.$loading.show()
      console.log(this.$loading)
      await this.$delay(1000, 1000)
      this.$loading.hide()
      if (is_web_code) {
        this.codearea = key
        this.residence = this.$root.area[key].children
      }
      this.init(this.org_type, key)
      this.setType('0')
      this.search_flag = false
      this.searchinfo = ''
    },
    setType(key) {
      this.search_flag = false
      this.searchinfo = ''
      this.dispute = key
      if (this.dispute === 0) {
        return
      }
      this.masData_dispute.length = 0
      for (var i = 0; i < this.masData.length; i++) {
        if (
          this.masData[i].dispute &&
          this.masData[i].dispute.toString() === key
        ) {
          let newitem = this.masData[i]
          newitem.index = i
          this.masData_dispute.push(newitem)
        }
      }
      this.show_select_area = false
    },
    // 跳到地图点，并显示改点信息
    getToPoint(index) {
      if (!this.masData.length) return
      const item = this.masData[index]
      const [lan, lng] = item.geography.split(',')
      const position = new this.qq.maps.LatLng(lan, lng)
      this.showlist = false
      this.selected = index
      this.infoWin.open()
      this.infoWin.setContent(this.setMapContent(item))
      this.infoWin.setPosition(position)
      this.map.panTo(position)
    },
    // 设置地图点信息模版
    setMapContent(item) {
      let { name, address, tell } = item
      if (!tell) {
        tell = '暂无'
      }
      const desc =
        this.org_type && item.desc
          ? '<strong>专业：</strong>' + item.desc + '<br>'
          : ''
      return `<div class="map-marker-info" style="padding:0 0 10px;">
          <h2 style="font-size:18px; margin:0 0 10px;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">${name}</h2>
          <div style="color:#808080; font-size:16px;">
            ${desc}
            <strong>地址：</strong>${address} <br>
            <strong>电话：</strong>${tell}
          </div>
        </div>`
    },
    // 初始化地图点
    async init(org_type, code) {
      // 获取api
      const { status, result, msg } = await this.$get(
        `https://yn.12348.laway.cn/pufa/api/organization/?org_type=${org_type}&code=${code}`,
        this
      )

      if (!status) {
        console.log('err:' + msg)
        return
      }
      const items = result.data

      // 判断是否取得用户位置
      // console.log(userLocation)
      // let userPosition = true
      // if (userLocation && userLocation[0]) {
      //   const { lat, lng } = userLocation[1]
      //   this.map_center = [lat, lng]
      //   userPosition = true
      // }
      // 设置地图
      const dom = document.querySelector('#map-container')
      if (dom.childNodes.length) {
        dom.childNodes[0].remove()
      }

      // 在此完成该函数
      const qq = await TMap('OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77')
      const map = new qq.maps.Map(dom, {
        center: new qq.maps.LatLng(...this.map_center),
        zoom: this.zoom
      })
      // 地图点信息
      const infoWin = new qq.maps.InfoWindow({ map, zIndex: 10000 })
      // 存储地图对象
      this.qq = qq
      this.map = map
      this.infoWin = infoWin
      // 是否获取用户信息，获取了则计算距离

      this.masData = this.getDistanceList(items)
      // 跳到的一个地图点中心，并打开信息
      this.getToPoint(0)
      const masData = this.masData
      this.markers_array = []
      if (!items.length) {
        this.masData = []
        this.markers_array = []
        return
      }
      // let { qq, map, infoWin } = this
      for (let i = 0; i < masData.length; i++) {
        const { geography } = masData[i]
        const [lan, lng] = geography.split(',')
        const position = new qq.maps.LatLng(lan, lng)
        const anchor = new qq.maps.Point(24, 50)
        const size = new qq.maps.Size(100, 100)
        const origin = new qq.maps.Point(0, 0)
        const scaleSize = new qq.maps.Size(48, 48)
        const icon = new qq.maps.MarkerImage(
          'static/img/icon/position.png',
          size,
          origin,
          anchor,
          scaleSize
        )
        // 添加marker
        const marker = new qq.maps.Marker({
          position,
          map,
          animation: qq.maps.MarkerAnimation.DOWN
        })
        const infotmp = this.setMapContent(masData[i])
        // 加载marker图标
        marker.setIcon(icon)
        this.markers_array.push(marker)
        // 添加点击事件
        qq.maps.event.addListener(marker, 'click', () => {
          infoWin.open()
          infoWin.setContent(infotmp)
          infoWin.setPosition(position)
        })
      }
      // 拖动地图后事件
      // qq.maps.event.addListener(map, 'dragend', event => infoWin.close())
      // await this.$delay(2000, 1000)
      // this.showlist = true
    },
    // 距离列表排讯
    getComputeList(arr) {
      let masdata = []
      getDistanceSortList(arr)
      arr.map(v => {
        let d =
          v.distance > 1000
            ? `（距离${(v.distance / 1000).toFixed(2)}公里）`
            : `（距离${parseInt(v.distance.toFixed(2))}米）`
        v.address += d
        masdata.push(v)
      })
      return masdata
    },
    // 计算距离列表
    getDistanceList(list) {
      const arr = []
      const [lat, lng] = this.map_center
      const qq = this.qq
      list.map((v, i) => {
        if (!v.geography) return
        let p = v.geography.split(',')
        let d = qq.maps.geometry.spherical.computeDistanceBetween(
          new qq.maps.LatLng(lat, lng),
          new qq.maps.LatLng(p[0], p[1])
        )
        v.distance = d
        arr.push(v)
      })
      return this.getComputeList(arr)
    },
    async getSearchedInfo() {
      if (this.searchinfo.length > 1) {
        let reg = /[\u4e00-\u9fa5]/
        let info = this.searchinfo
        for (let char of this.searchinfo) {
          if (!reg.test(char)) {
            info = info.replace(char, '')
          }
        }
        if (info.length === 0) {
          this.search_flag = false
          return
        }
        this.search_flag = true
        this.masData_search.length = 0
        if (this.dispute === '0') {
          for (let i = 0; i < this.masData.length; i++) {
            if (this.masData[i].name.includes(info)) {
              let newitem = this.masData[i]
              newitem.index = i
              this.masData_search.push(newitem)
            }
          }
        } else {
          for (let i = 0; i < this.masData_dispute.length; i++) {
            if (this.masData_dispute[i].name.includes(info)) {
              let newitem = this.masData_dispute[i]
              this.masData_search.push(newitem)
            }
          }
        }
      } else {
        this.search_flag = false
      }
    },
    filteredTell(tell) {
      if (!tell) {
        return '暂无'
      }
      if (tell.includes(';')) {
        return tell.split(';')[0]
      } else if (tell.includes('')) {
        return tell.split(' ')[0]
      }
    }
  },
  filters: {
    typename(org_type) {
      return org_type_name[org_type]
    }
  },
  watch: {
    searchinfo() {
      this.searchinfo = this.searchinfo.replace(' ', '')
      this.getSearchedInfo()
    }
  },
  components: {
    Menus,
    Dialogs
  },
  async mounted() {
    const { area, config, point } = this.$root
    console.log(point)
    console.log(area)
    this.residence = area[config.web_code].children
    this.map_center = point.geography.split(',')
    const org_type = this.$route.params.org_type

    // console.log(servicePosition)

    this.org_type = org_type
    console.log('org_type:', this.org_type)
    // if (org_type === '2') {
    //   if (servicePosition.code === 530100) {
    //     this.show_select_area = true
    //   } else {
    //     this.code = servicePosition.code
    //     this.init(org_type, servicePosition.code)
    //     this.setType('0')
    //   }
    // } else {
    //   this.setArea('530100')
    // }
    this.setArea(config.web_code, true)
    // this.init(org_type)
    // 设置中心坐标，从服务点获取

    // const data = await this.$get(api.map + org_type, this)
    // this.masData = data
    // this.name = typename[org_type]
    // this.init()
  }
}
</script>
<style lang="scss">
.select_area {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 10000;
  background: rgba(0, 0, 0, 0.5);
  .wrap {
    background: #fff;
    border-radius: 0.1rem;
    width: 12rem;
    margin: 0.25rem auto;
    padding: 0.35rem;
    text-align: center;
    .ht {
      font-size: 0.28rem;
      padding-bottom: 0.2rem;
      color: #555;
    }
    .content {
      display: flex;
      flex-wrap: wrap;
      a {
        width: 33.33%;
        span {
          padding: 0.15rem 0;
          display: block;
          font-size: 0.2rem;
          background: #eee;
          margin: 0 0.1rem 0.1rem 0;
        }
      }
    }
  }
}
#map {
  height: 100vh;
  .map-wrap {
    padding-top: 1.6rem;
    display: flex;
    height: 100%;
    .map-area-list {
      background: #fff;
      width: 30%;
      overflow-y: scroll;
      box-shadow: 0.1rem 0 0.1rem rgba(0, 0, 0, 0.1);
      position: relative;
      z-index: 100;
    }
  }
}
.service-content {
  background: #fff;
  position: relative;
  .choose-service {
    div.ht {
      padding-top: 1rem;
      padding-bottom: 0.1rem;
      border-bottom: 1px solid #ccc;
      color: #999;
      margin-bottom: 0.15rem;
      font-size: 0.16rem;
    }
    a {
      margin-bottom: 0.1rem;
    }
  }
  .choose-item {
    padding-top: 0.1rem;
    .content-block-title {
      padding: 0.15rem;
      font-size: 0.16rem;
    }
    .search-content {
      padding: 0 0.15rem 0.15rem;
    }
    .option-area-select {
      padding: 0 0 0.15rem 0.15rem;
      a.btn {
        margin: 0 0.1rem 0.1rem 0;
      }
    }
    .reback {
      position: fixed;
      left: 0;
      top: 0;
      width: 2.6rem;
      a {
        display: inline-block;
        padding: 0.2rem;
      }
    }
    .list-block {
      margin: 0 0 0.75rem;
      ul {
        padding: 0;
        list-style: none;
      }
      .item-content {
        display: block;
        border-top: 1px solid #ddd !important;
        &.on {
          background: #eee;
        }
        &:active {
          background: #eee;
        }
      }
      .item-inner {
        padding: 0.15rem;
      }
      .item-title {
        white-space: normal;
        .ht {
          font-weight: normal;
          display: block;
          padding-bottom: 0.05rem;
          display: flex;
          align-items: center;
          span {
            width: 0.36rem;
            height: 0.43rem;
            line-height: 0.36rem;
            display: block;
            margin-right: 0.05rem;
            background-image: url('https://ynterminal.laway.cn/static/img/icon/map.png');
            background-size: 0.36rem 0.43rem;
            text-align: center;
            color: #fff;
            font-size: 0.18rem;
            flex-shrink: 0;
          }
          strong {
            width: auto;
            font-size: 0.18rem;
          }
        }
        p {
          color: #999;
          margin: 0;
          font-size: 0.16rem;
        }
      }
    }
    .tips {
      margin: 0 0.15rem;
      padding-top: 0.15rem;
      border-top: 1px dashed #ccc;
      font-size: 0.18rem;
      color: #999;
    }
  }
}

#map-container {
  min-height: 9.2rem;
  width: 70%;
  .map-marker-current {
    left: 50%;
    top: 4.6rem;
    position: relative;
    width: 0.5rem;
    height: 0.5rem;
    margin: -0.25rem 0 0 -0.25rem;
    z-index: 10000;
  }
  .map-marker-info {
    // text-align: center;
    // white-space: nowrap;
    margin: 0.1rem;
    h2 {
      font-size: 0.2rem;
      color: #3d69bd;
    }
    div {
      font-size: 0.16rem;
      p {
        margin: 0;
        strong {
          color: #f1543f;
          font-weight: normal;
        }
      }
    }
  }
}
</style>
